<script setup>
import { ref } from 'vue'
import { userLoginService } from '@/api/user.js'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../stores'
import { ElMessage, ElMessageBox } from "element-plus";

//声明表单
const form = ref({
  account: '',
  password: ''
})

const router = useRouter()

const userStore = useUserStore()

const formRef = ref()

//声明表单校验规则
const rules = {
  account: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ]
}

//声明登录函数
const login = async () => {
  await formRef.value.validate()
  const res = await userLoginService(form.value)
  if (res.code === '200') {
    userStore.setUser(res.data)
    ElMessage({
      type: "success",
      message: '登录成功',
    });
    if (res.data.role === 'student'){
      await router.push('/layout');
    }
    if (res.data.role === 'parent'){
      await router.push('/parent/layout');
    }
    if (res.data.role === 'teacher'){
      await router.push('/teacher/layout');
    }
    if (res.data.role === 'admin'){
      await router.push('/admin/layout');
    }
  } else {
    ElMessage({
      type: "error",
      message: res.msg,
    });
  }
}

</script>

<template>
  <div style="height: 100vh;display: flex;align-items: center;justify-content: center;background-color:#dfdfdf">
    <div style="display: flex;background-color: white;width: 50%;border-radius: 5px;overflow: hidden;">
      <div style="flex: 1;">
        <img src="@/assets/imgs/login.png" style="width: 100%;">
      </div>
      <div style="flex: 1;display: flex;align-items: center;justify-content: center;">

        <el-form :model="form" :rules="rules" style="width: 80%;" ref="formRef">
          <div style="font-size: 18px;font-weight: bold;text-align: center;margin-bottom: 20px">基于大型语言模型的智能考题生成系统</div>
          <el-form-item prop="account">
            <el-input prefix-icon="user" size="medium" placeholder="请输入账号" v-model="form.account" ></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="lock" size="medium" show-password placeholder="请输入密码"
              v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%;" @click="login">登录</el-button>
          </el-form-item>
          <div style="display: flex;">
            <div style="flex: 1;">还没有账号?请<span style="color: #0f9876;cursor: pointer;"
                @click="$router.push('/register')">注册</span></div>
<!--            <div style="flex: 1;text-align: right;"><span style="color: #0f9876;cursor: pointer;">忘记密码</span></div>-->
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
